package com.carkeeper.discover.service.impl;

import com.carkeeper.common.utils.IdWorker;
import com.carkeeper.common.utils.StatusCode;
import com.carkeeper.discover.mapper.DiscoverMapper;
import com.carkeeper.discover.service.DiscoverService;
import com.carkeeper.pojo.Blog;
import com.carkeeper.pojo.BlogCategory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;
import tk.mybatis.mapper.entity.Example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class DiscoverServiceImpl implements DiscoverService {
    @Autowired
    private DiscoverMapper discoverMapper;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BlogCategoryServiceImpl blogCategoryService;


    /**
     * 添加文稿
     *
     * @param map
     */
    @Transactional
    @Override
    public void add(Map map) {
        String creator = "张三";//以后从springsecrity中取
        //将数据封装为blog对象
        long id = idWorker.nextId();
        System.out.println(id);
        Blog blog = this.mapToBlog(map);
        blog.setId(String.valueOf(id));
        blog.setCreator(creator);
        blog.setStatus(StatusCode.BLOG_PUBLISHED);
        blog.setCreateTime(new Date());
        blog.setUpdateTime(new Date());

        discoverMapper.insertSelective(blog);
    }

    /**
     * 条件分页查询
     * 无条件时查询所有
     */
    @Override
    public Map<String, Object> findPage( int page, int size, Map searchMap) {
        Example example = this.createExample(searchMap);
        PageHelper.startPage(page, size);
        List<Blog> blogs = discoverMapper.selectByExample(example);
        PageInfo<Blog> info = new PageInfo(blogs);
        Map<String, Object> resultMap = getResultMap(info);
        return resultMap;
    }

    /**
     * 修改文稿
     *
     * @param map
     */
    @Override
    @Transactional
    public void update(Map map) {
        Blog blog = this.mapToBlog(map);
        //前台点击取消发布,传status=0;
        if (map.get("status") != null && (Integer) map.get("status") == 0) {
            blog.setStatus(StatusCode.BLOG_UNPUBLISHED);
        }
        //前台点击发布,传出status=1;
        if (map.get("status") != null && (Integer) map.get("status") == 1) {
            blog.setStatus(StatusCode.BLOG_PUBLISHED);
        }
        blog.setId((String) map.get("id"));
        blog.setUpdateTime(new Date());
        discoverMapper.updateByPrimaryKeySelective(blog);
    }


    /**
     * 根据id查询详情
     *
     * @param id
     * @return
     */
    @Override
    public Map findById(String id) {
        Blog blog = discoverMapper.selectByPrimaryKey(id);
        Map map = this.getDetailResult(blog);
        return map;
    }

    /**
     * 查询返回数据封装
     */
    public Map<String, Object> getResultMap(PageInfo<Blog> info) {
        Map<String, Object> resultMap = new HashMap();
        List<Map> list = new ArrayList<>();
        //封装传给前台的数据
        for (Blog blog : info.getList()) {
            Map map = this.getDetailResult(blog);
            list.add(map);
        }
        resultMap.put("records", list);

        resultMap.put("total", info.getTotal());//总记录数
        resultMap.put("size", info.getPageSize());//每页数量
        resultMap.put("current", info.getPageNum());//当前页
        resultMap.put("searchCount", info.getPageSize());//查询总数
        resultMap.put("pages", info.getPages());//总页数
        return resultMap;
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Blog.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 标题
            if (searchMap.get("title") != null && !"".equals(searchMap.get("title"))) {
                criteria.andLike("title", "%" + (String) (searchMap.get("title")) + "%");
            }
            // 标题图片
            if (searchMap.get("cover") != null && !"".equals(searchMap.get("cover"))) {
                criteria.andEqualTo("cover", "%" + searchMap.get("cover") + "%");
            }
            //分类id
            if (searchMap.get("blogCategoryId") != null) {
                criteria.andLike("blogCategoryId", "%" + searchMap.get("blogCategoryId") + "%");
            }

            // 排序 //1表示正序,2表示倒序
            if (searchMap.get("sort") != null) {
                if (1 == (int) (searchMap.get("sort"))) {
                    example.setOrderByClause("id ASC");
                }
                if (2 == (int) (searchMap.get("sort"))) {
                    example.setOrderByClause("id DESC");
                }
            }
            // 连接
            if (searchMap.get("link") != null && !"".equals(searchMap.get("link"))) {
                criteria.andEqualTo("link", searchMap.get("link"));
            }
            //状态
            if (searchMap.get("status") != null) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }
            //发布人
            if (searchMap.get("creator") != null && !"".equals(searchMap.get("creator"))) {
                criteria.andEqualTo("creator", searchMap.get("creator"));
            }
            //

            if (searchMap.get("startTime") != null && searchMap.get("endTime") != null) {
                //开始时间小于创建时间
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
                String startTime = (String) searchMap.get("startTime");
                String endTime = (String) searchMap.get("endTime");
                Date startTime1 = null;
                Date endTime1 = null;
                try {
                    startTime1 = simpleDateFormat.parse(startTime);
                    endTime1 = simpleDateFormat.parse(endTime);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                //
                criteria.andLessThanOrEqualTo("createTime", endTime1);

                //创建时间大于开始时间
                criteria.andGreaterThanOrEqualTo("createTime", startTime1);

                // criteria.andBetween("createTime",startTime1,endTime1);
            }

        }
        return example;
    }

    /**
     * 封装返回数据
     */
    public Map getDetailResult(Blog blog) {
        Map<String, Object> map = new HashMap();
        Integer blogCategoryId = blog.getBlogCategoryId();
        map.put("id", blog.getId());
        map.put("title", blog.getTitle());
        map.put("cover", blog.getCover());
        map.put("createTime", blog.getCreateTime());
        map.put("index", blog.getSort());
        map.put("link", blog.getLink());
        map.put("content", blog.getContent());
        if (blogCategoryId != null) {
            BlogCategory blogCategory = blogCategoryService.findById(blogCategoryId);
            if (blogCategory != null) {
                map.put("categoryName", blogCategory.getName());
            }
        }
        map.put("creator", blog.getCreator());
        map.put("status", blog.getStatus());
        return map;
    }

    /**
     * 将前台传的map数据封装为Blog
     *
     * @param map
     * @return
     */
    public Blog mapToBlog(Map map) {
        Blog blog = new Blog();
        blog.setTitle((String) map.get("title"));
        blog.setCover((String) map.get("cover"));
        String categoryName = (String) map.get("categoryName");
        if (categoryName != null && !"".equals(categoryName)) {
            Integer CategoryId = blogCategoryService.findIdByName(categoryName);
            blog.setBlogCategoryId(CategoryId);
        }
        blog.setSort((Integer) map.get("index"));
        blog.setLink((String) map.get("link"));
        blog.setContent((String) map.get("content"));

        return blog;
    }

}
